package com.learn.demo.netty.codec;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufEncoder;


public class NettyClient4ProtoBufDemo {
    public static void main(String[] args) {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(workerGroup)
                    //设置客户端通道类型
                    .channel(NioSocketChannel.class)
                    //设置保持活动连接状态
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    //设置处理器
                    .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    //添加编码器
                    pipeline.addLast("encoder", new ProtobufEncoder());
                    //自定义handler
                    pipeline.addLast(new NettyClientHandlerDemo());
                }
            });
            System.out.println("Client is ready...");
            //绑定服务器地址和端口，并启动客户端
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6666).sync();

            //监听客户端通道关闭
            channelFuture.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            //关闭资源
            workerGroup.shutdownGracefully();
        }
    }
}
